package com.kui.controller;

import com.kui.annotation.AuthCheck;
import com.kui.common.BaseResponse;
import com.kui.common.ResultUtils;
import com.kui.constant.UserConstant;
import com.kui.exception.BusinessException;
import com.kui.exception.ErrorCode;
import com.kui.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RequestMapping("/file")
@RestController
@Slf4j
@Api(value = "文件管理", tags = "文件管理")
public class FileController {
    @Resource
    private CosManager cosManager;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    public BaseResponse<?> upload(@RequestPart("file") MultipartFile multipartFile) {
        log.info("文件上传执行中........");
        // 拿到文件原名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 拼接文件路径
        String filePath = String.format("/test/%s", originalFilename);
        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(filePath, null);
            // 将文件保存到临时文件中
            multipartFile.transferTo(file);
            // 上传到cos
            cosManager.putObject(filePath, file);
            // 返回可访问地址
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error, filePath = ", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filePath= {}", filePath);
                }
            }
        }
    }

    /**
     * 文件下载
     *
     * @param filePath
     * @param response
     */
    @GetMapping("download")
    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    public void download(String filePath, HttpServletResponse response) throws Exception {
        log.info("文件下载执行中.........");
        COSObjectInputStream objectInputStream = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            objectInputStream = cosObject.getObjectContent();
            //转换成字节数组
            byte[] bytes = IOUtils.toByteArray(objectInputStream);
            //  设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭流
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        }
    }
}
